package com.onstar.cn.weight;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Button 倒计时
 */
public class TimeButton extends Button {
    private TimeCount time;
    // 完成后显示文字
    private String finishText;

    /**
     * @Description: 倒计时按钮
     * @author Mengting Lu
     * @date 2015年8月6日 下午4:07:39
     */
    public TimeButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public TimeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimeButton(Context context) {
        super(context);
    }

    /**
     * @return void
     * @throws
     * @Title: start
     * @Description: 开启计时器><br/>
     * text 倒计时完成后显示文字
     */
    public void start(String text) {
        this.finishText = text;
        time = new TimeCount(60000, 1000);
        time.start();
    }

    public void start(int resId) {
        start(getResources().getString(resId));
    }

    private ResultListener resultListener;

    public void setResultListener(ResultListener resultListener) {
        this.resultListener = resultListener;
    }

    public interface ResultListener {
        void end();

        void inProgress();
    }

    class TimeCount extends CountDownTimer {

        /**
         * @Description: TODO
         * @author Mengting Lu
         * @date 2015年8月6日 下午4:10:59
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        /**
         * (non-Javadoc)
         * <p>
         * Title: onTick
         * </p>
         * <p>
         * Description:
         * </p>
         *
         * @param millisUntilFinished
         * @see android.os.CountDownTimer#onTick(long)
         */
        @Override
        public void onTick(long millisUntilFinished) {
            TimeButton.this.setClickable(false);
            TimeButton.this.setText(getResources().getString(R.string.again_send) + "("+millisUntilFinished / 1000 + ")");
            TimeButton.this.setTextColor(getResources().getColor(R.color.fontColorGray));
        }

        /**
         * (non-Javadoc)
         * <p>
         * Title: onFinish
         * </p>
         * <p>
         * Description:
         * </p>
         *
         * @see android.os.CountDownTimer#onFinish()
         */
        @Override
        public void onFinish() {
            setText(finishText);
            setClickable(true);
            if (resultListener != null) {
                resultListener.end();
            }
        }

    }

}
